package com.sec.android.app.myfiles.module.local.foldertree;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.feature.PrivateModeMgr;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppConstants.StoragePath;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.AbsFileListAdapterImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.CloudType;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.module.cloud.CloudFileRecord;
import com.sec.android.app.myfiles.module.local.file.LocalFileRecord;
import com.sec.android.app.myfiles.module.shortcut.ShortcutFileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.provider.DbTableInfo.COLUMN_ID;
import com.sec.android.app.myfiles.thumbnail.ThumbnailImageView;
import com.sec.android.app.myfiles.thumbnail.ThumbnailMgr;
import com.sec.android.app.myfiles.util.FileUtils;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;
import com.sec.android.app.myfiles.widget.listview.AbsListViewImp;
import com.sec.android.app.myfiles.widget.listview.FolderTreeHolder;
import com.sec.android.app.myfiles.widget.listview.ListViewHolder;

public class FolderTreeListAdapterImp extends AbsFileListAdapterImp {
    private FileRecord mCurOpeningRecord;
    private NavigationInfo mCurNavigationInfo;

    public FolderTreeListAdapterImp(Context context, NavigationInfo navigationInfo, AbsListViewImp listView, Cursor c, int flags) {
        super(context, navigationInfo, listView, c, flags);
    }


    @Override
    public String getSelection() {
        boolean showHidden = PreferenceUtils.getShowHiddenFiles(mContext);
        String strRet = mTableInfo.getColumnName(COLUMN_ID.PATH) + " like ?";
        if (!showHidden) {
            strRet = strRet + " AND " + mTableInfo.getColumnName(COLUMN_ID.IS_HIDDEN) + "=0";
        }
        return strRet;
    }

    @Override
    public String[] getSelectionArgs() {
        String path = mNavigationInfo.getCurRecord().getFullPath();
        return new String[]{path + "%"};
    }

    @Override
    public String getOrderBy() {
        return null;
    }

    @Override
    public StorageType getStorageType() {
        return StorageType.FolderTree;
    }

    @Override
    protected FileRecord _getFileRecord(Cursor cursor) {
        FileRecord ret = null;

        final int pathIndex = mTableInfo.getIndex(COLUMN_ID.PATH);
        final int nameIndex = mTableInfo.getIndex(COLUMN_ID.NAME);
        final int dateIndex = mTableInfo.getIndex(COLUMN_ID.DATE);
        final int hiddenIndex = mTableInfo.getIndex(COLUMN_ID.IS_HIDDEN);
        final int cntIndex = mTableInfo.getIndex(COLUMN_ID.ITEM_COUNT);
        final int cntHiddenIndex = mTableInfo.getIndex(COLUMN_ID.ITEM_COUNT_HIDDEN);
        final int isOpened = mTableInfo.getIndex(COLUMN_ID.OPENED);
        final int fileTypeIndex = mTableInfo.getIndex(COLUMN_ID.FILE_TYPE);
        final int storageTypeIndex = fileTypeIndex + 1;

        if (cursor != null) {

            String path = cursor.getString(pathIndex);
            String name = cursor.getString(nameIndex);
            long date = cursor.getLong(dateIndex);
            int fileType = cursor.getInt(fileTypeIndex);
            int isHidden = cursor.getInt(hiddenIndex);
            int itemCount = cursor.getInt(cntIndex);
            int itemCountHidden = cursor.getInt(cntHiddenIndex);
            int opened = cursor.getInt(isOpened);
            int storageType = cursor.getInt(storageTypeIndex);

            StorageType storage = StorageType.values()[storageType];

            ret = FileRecord.createFileRecord(storage, -1, path, name, 0, date, fileType, isHidden, itemCount, itemCountHidden);

            if (ret instanceof FolderTreeRecord) {
                ((FolderTreeRecord) ret).setOpened(opened != 0);
            }
        }

        return ret;
    }


    @Override
    public String getFilePath(Cursor cursor) {
        return getFilePath(cursor, mTableInfo.getIndex(COLUMN_ID.PATH), mTableInfo.getIndex(COLUMN_ID.NAME));
    }

    protected void _bindView(Context context, ListViewHolder vh, View v, FileRecord record, int position) {
        View itemArea = vh.getView(FolderTreeHolder.ITEM_AREA);
        View itemDivider = vh.getView(FolderTreeHolder.ITEM_DIVIDER);

        if (itemArea != null) {
            itemArea.setVisibility(View.VISIBLE);
        }
        if (itemDivider != null) {
            itemDivider.setVisibility(View.GONE);
        }

        _bindCheckView(context, vh, record);

        _bindMenuItem(context, record, vh, v);

        if (record.getStorageType() == StorageType.Cloud) {
            boolean enable = _bindCloudItem(vh.getView(FolderTreeHolder.SUB_TEXT, TextView.class), ((CloudFileRecord) record).getCloudType());
            enableView(v, enable);
        } else {
            View subText = vh.getView(FolderTreeHolder.SUB_TEXT, TextView.class);
            if (subText != null) {
                subText.setVisibility(View.GONE);
            }
        }
        setItemEnabled(vh, v, record);

    }

    @Override
    public boolean _isEnabled(int position) {
        FileRecord record = getFileRecord(position);
        return !UiUtils.isSectionDivider(record);
    }

    @Override
    public boolean areAllItemsEnabled() {
        return false;
    }

    @Override
    protected void _bindNullView(Context context, ListViewHolder vh, View v, FileRecord record, int position) {
        View ItemArea = vh.getView(FolderTreeHolder.ITEM_AREA);
        TextView ItemDivider = (TextView) vh.getView(FolderTreeHolder.ITEM_DIVIDER);

        if (ItemArea != null) {
            ItemArea.setVisibility(View.GONE);
        }

        if (ItemDivider != null) {
            ItemDivider.setVisibility(View.VISIBLE);
            ItemDivider.setText(getNullViewName(record.getStorageType()));
        }
    }

    private String getNullViewName(StorageType type) {
        String name = null;
        if (type == StorageType.Category) {
            name = mContext.getString(R.string.subtitle_category);
        } else if (type == StorageType.FolderTree) {
            if (AppFeatures.isTablet()) {
                name = mContext.getString(R.string.tablet);
            } else {
                name = mContext.getString(R.string.phone);
            }
        } else if (type == StorageType.Cloud) {
            name = mContext.getString(R.string.cloud);
        } else if (type == StorageType.Shortcut) {
            name = mContext.getString(R.string.sheader_shortcuts);
        }
        return name;
    }

    private void _bindMenuItem(Context context, FileRecord record, ListViewHolder vh, View v) {
        ThumbnailImageView thumbnailView = vh.getView(FolderTreeHolder.THUMBNAIL, ThumbnailImageView.class);
        ImageView iconView = vh.getView(FolderTreeHolder.FILE_TYPE_ICON, ImageView.class);
        TextView textView = vh.getView(FolderTreeHolder.NAME, TextView.class);
        if (thumbnailView != null && iconView != null && mNavigationInfo != null) {
            thumbnailView.setThumbnailView(mNavigationInfo.getCurFragment(), record, v);
            if (record.getStorageType() == StorageType.Shortcut && !record.isDirectory()) {
                thumbnailView.clearColorFilter();
                iconView.clearColorFilter();
                View view;
                if (record.isApkFileType()) {
                    view = ThumbnailMgr.getInstance(context).loadThumbnail(record, thumbnailView, iconView);
                } else {
                    view = ThumbnailMgr.getInstance(context).loadThumbnail(record, thumbnailView, thumbnailView);
                }
                if (view == null) {
                    iconView.setImageDrawable(MediaFile.getFileTypeDrawable(context, record));
                }
            } else {
                thumbnailView.setImageBitmap(null);
                UiUtils.setHomeItemIcon(context, record, iconView);
            }
        }
        if (textView != null) {
            String name = record.getDisplayName(context);
            textView.setText(name);
        }
    }

    private boolean _bindCloudItem(TextView subTextView, CloudType cloudType) {
        boolean bRet = false;
        if (subTextView != null) {
            subTextView.setVisibility(View.VISIBLE);

            CloudMgr cloudMgr = CloudMgr.getInstance(mContext);
            if (!cloudMgr.isAccountRetrieved(cloudType)) {
                subTextView.setText(R.string.not_signed_in);
            } else {
                bRet = true;
                String signedUserId = cloudMgr.getUserId(cloudType);

                if ((signedUserId == null) || signedUserId.isEmpty()) {
                    subTextView.setText(cloudMgr.isSignedIn(cloudType) ? R.string.retrieving_account : R.string.not_signed_in);
                } else {
                    subTextView.setText(signedUserId);
                }
            }
        }
        return bRet;
    }

    private void _bindCheckView(Context context, ListViewHolder vh, FileRecord record) {
        int childDirCount;
        View depthView = vh.getView(FolderTreeHolder.DEPTH_VIEW);
        ImageView openerView = vh.getView(FolderTreeHolder.EXPAND_VIEW, ImageView.class);

        if (depthView != null && openerView != null) {
            int nDepth = getDepth(record);
            int width = mContext.getResources().getDimensionPixelSize(R.dimen.tree_view_list_item_expand_indicator_margin_start);
            int depthWidth = mContext.getResources().getDimensionPixelSize(R.dimen.tree_view_list_item_depth_width);
            width += nDepth * depthWidth;

            OnClickListener listener = null;
            FileRecord targetRecord = null;

            LayoutParams param = depthView.getLayoutParams();
            param.width = width;
            depthView.setLayoutParams(param);

            if (record instanceof LocalFileRecord) {
                listener = mIndicatorClickListener;
                targetRecord = record;
                boolean isRoot = record.isRoot();
                if (isRoot) {
                    targetRecord = FileRecord.createFileRecord(StorageType.FolderTree, record.getFullPath());
                }
            } else if (record instanceof FolderTreeRecord) {
                FolderTreeRecord folderRecord = (FolderTreeRecord) record;
                boolean showHidden = PreferenceUtils.getShowHiddenFiles(context);

                childDirCount = folderRecord.hasChildDirCount(showHidden);
                if (childDirCount > 0) {
                    listener = mIndicatorClickListener;
                    targetRecord = record;
                    openerView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
                } else {
                    openerView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
                }
            } else {
                openerView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
            }

            if (targetRecord != null) {
                openerView.setVisibility(View.VISIBLE);
                openerView.setImageResource(R.drawable.myfiles_list_ic_arrow);
                float rotation = 0;
                if (targetRecord instanceof FolderTreeRecord && ((FolderTreeRecord) targetRecord).isOpened()) {
                    openerView.setContentDescription(context.getResources().getString(R.string.collapse));
                } else {
                    rotation = UiUtils.isInRTLMode(mContext) ? 90 : -90;
                    openerView.setContentDescription(context.getResources().getString(R.string.expand));
                }
                FileRecord openRecord = getOpeningRecord();
                if (openRecord != null && openRecord.equals(targetRecord)) {
                    openerView.animate().rotation(rotation).setDuration(300);
                    setOpeningRecord(null);
                } else {
                    openerView.setRotation(rotation);
                }
            } else {
                openerView.setVisibility(View.INVISIBLE);
                openerView.setImageDrawable(null);
            }
            openerView.setTag(targetRecord);
            openerView.setOnClickListener(listener);

            depthView.setTag(targetRecord);
            depthView.setOnClickListener(listener);
            depthView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
        }
    }

    private void setItemEnabled(ListViewHolder vh, View view, FileRecord record) {
        ImageView openerView = vh.getView(FolderTreeHolder.EXPAND_VIEW, ImageView.class);
        View depthView = vh.getView(FolderTreeHolder.DEPTH_VIEW);
        boolean enable = true;
        StorageType storageType = record.getStorageType();
        if (mCurNavigationInfo != null) {
            String path = record.getFullPath();
            if (mCurNavigationInfo.isSelectOpDestination()) {
                if (storageType == StorageType.FolderTree) {
                    if (mCurNavigationInfo.isRemoveFromPrivate() && path.startsWith(PrivateModeMgr.getInstance(mContext).getRootDir())) {
                        enable = false;
                    }
                } else if (storageType == StorageType.Recent) {
                    enable = false;
                } else if (storageType == StorageType.Category) {
                    enable = false;
                } else if (storageType == StorageType.Downloads) {
                    enable = false;
                }
            } else if (mCurNavigationInfo.isCompressPreview()) {
                enable = false;
            } else if (mCurNavigationInfo.getCurFragment() != null && mCurNavigationInfo.getCurFragment().isDragtStarted()) {
                if (storageType != StorageType.FolderTree && storageType != StorageType.Shortcut) {
                    enable = false;
                } else {
                    enable = FileUtils.isPrivateFolder(mCurNavigationInfo.getCurRecord().getFullPath()) ? FileUtils.isPrivateFolder(path) : true;
                }
            } else if (mCurNavigationInfo.isCreateDocument() || mCurNavigationInfo.isSelectDestinationPath()) {
                if (storageType == StorageType.FolderTree) {
                    if (!path.startsWith(StoragePath.INTERNAL_ROOT)) {
                        enable = false;
                    }
                } else {
                    enable = false;
                }
            }
        }

        if (storageType == StorageType.Cloud && enable) {
            enable = StorageMonitor.getDeviceStorageFreeSpace() > AppConstants.AVAILABLE_DEVICE_STORAGE_FREE_SPACE;
        }

        enableView(view, enable);

        if (openerView != null) {
            openerView.setEnabled(enable);
        }

        if (depthView != null) {
            depthView.setEnabled(enable);
        }
    }

    private void enableView(View view, boolean bEnable) {
        if (view != null) {
            view.setClickable(!bEnable);
            view.setEnabled(bEnable);
            view.setAlpha(bEnable ? 1.0f : 0.4f);
        }
    }

    private final OnClickListener mIndicatorClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            FileRecord record = (FileRecord) v.getTag();
            if (record != null) {
                if (mNavigationInfo.getCurFragment() != null) {
                    Log.d(this, "indicator :" + record.getFullPath());
                    MyFilesFacade.openFolderTree(mNavigationInfo.getCurFragment().getProcessId(), mContext, record);
                    setOpeningRecord(record);
                }
            }
        }
    };

    private void setOpeningRecord(FileRecord record) {
        mCurOpeningRecord = record;
    }

    private FileRecord getOpeningRecord() {
        FileRecord ret = mCurOpeningRecord;
        if (ret == null) {
            ret = getCurNavigatedRecord();
        }
        return ret;
    }

    private FileRecord getCurNavigatedRecord() {
        FileRecord ret = null;
        if (mNavigationInfo.getCurFragment() != null) {
            int processId = mNavigationInfo.getCurFragment().getProcessId();
            NavigationInfo naviInfo = NavigationManager.getInstance(processId).getCurInfo();
            if (naviInfo != null) {
                ret = naviInfo.getCurRecord();
                if (ret != null && ret.getStorageType() == StorageType.Local) {
                    ret = FileRecord.createFileRecord(StorageType.FolderTree, ret.getFullPath());
                }
            }
        }

        return ret;
    }

    public void setCurNavigationInfo(NavigationInfo navigationInfo) {
        mCurNavigationInfo = navigationInfo;
    }

    private int getDepth(FileRecord record) {
        String fullPath = record.getFullPath();
        int nStartIndex = 0;
        int nRet = 0;

        if (!(record instanceof ShortcutFileRecord)) {
            if (fullPath.startsWith(StoragePath.ROOT)) {
                nStartIndex = StoragePath.ROOT.length();

                if (fullPath.startsWith(StoragePath.EMULATED_ENTRY_FOLDER)) {
                    nStartIndex = StoragePath.EMULATED_ENTRY_FOLDER.length();
                }
            }

            nStartIndex = fullPath.indexOf('/', nStartIndex + 1);

            if (nStartIndex > 0) {
                fullPath = fullPath.substring(nStartIndex);
                nRet = fullPath.length() - fullPath.replace("/", "").length();
            }
        }

        return nRet;
    }

    @Override
    protected ListViewHolder _createViewHolder(View v) {
        ListViewHolder vh = ListViewHolder.createHolder(FolderTreeHolder.MAX);

        vh.addView(FolderTreeHolder.ITEM_AREA, v.findViewById(R.id.contents_container));
        vh.addView(FolderTreeHolder.ITEM_DIVIDER, v.findViewById(R.id.item_divider));
        vh.addView(FolderTreeHolder.DEPTH_VIEW, v.findViewById(R.id.empt_view_for_depth));
        vh.addView(FolderTreeHolder.EXPAND_VIEW, v.findViewById(R.id.tree_view_expand_indicator));
        vh.addView(FolderTreeHolder.NAME, v.findViewById(R.id.file_name));
        vh.addView(FolderTreeHolder.SUB_TEXT, v.findViewById(R.id.sub_text));
        vh.addView(FolderTreeHolder.THUMBNAIL, v.findViewById(R.id.thumbnail));
        vh.addView(FolderTreeHolder.FILE_TYPE_ICON, v.findViewById(R.id.file_type_icon));

        return vh;
    }

    @Override
    public void toggleExpand(int position) {
        if (mNavigationInfo.getCurFragment() != null) {
            FileRecord record = getFileRecord(position);
            MyFilesFacade.openFolderTree(mNavigationInfo.getCurFragment().getProcessId(), mContext, record);
            setOpeningRecord(record);
        }
    }
}
